from docx import Document
import re
import os

class DocxConverter:
    def __init__(self):
        self.content = ""
    
    def convert_docx_to_md(self, docx_path, add_title=False):
        """将docx文件转换为markdown格式"""
        doc = Document(docx_path)
        content = []
        
        # 如果需要，添加文件名作为一级标题
        if add_title:
            filename = os.path.splitext(os.path.basename(docx_path))[0]
            content.append('# ' + filename)
            content.append('')  # 标题后添加空行
        
        # 提取文档内容
        for paragraph in doc.paragraphs:
            text = paragraph.text.strip()
            if text:
                # 处理标题样式
                if paragraph.style.name.startswith('Heading'):
                    level = paragraph.style.name[-1]
                    content.append('#' * int(level) + ' ' + text)
                    content.append('')  # 标题后添加空行
                else:
                    # 处理段落内的换行
                    if paragraph._element.xpath("./w:br"):
                        lines = re.split(r'\n+', text)
                        formatted_lines = []
                        for i, line in enumerate(lines):
                            if i < len(lines) - 1:  # 不是最后一行
                                formatted_lines.append(line.strip() + '  ')  # 添加两个空格表示换行
                            else:
                                formatted_lines.append(line.strip())
                        content.append('\n'.join(formatted_lines))
                    else:
                        # 普通段落
                        content.append(text)
                    content.append('')  # 段落间添加空行
        
        self.content = '\n'.join(content)
        return self.content
    
    def save_to_md(self, output_path, content):
        """保存内容到markdown文件"""
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(content) 